package com.pubinfo.passbook.common.service.mss.impl;

import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.model.http.GetReimbursementInformation.ReimbursementInformation;
import com.pubinfo.passbook.common.model.http.GetReimbursementInformation.WriteoffInstance;
import com.pubinfo.passbook.common.model.http.GetReimbursementInformation.WriteoffInstanceCode;
import com.pubinfo.passbook.common.service.mss.WriteoffInstanceService;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class WriteoffInstanceServiceImpl implements WriteoffInstanceService {
  
  @Override
  public ReimbursementInformation getReimbursementInformationByDate(String date) throws UnirestException, ParseException {
    System.err.println(date);
    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
    WriteoffInstance writeoffInstance = new WriteoffInstance();
    writeoffInstance.setBeginDate(sd.parse(date));
    writeoffInstance.setEndDate(sd.parse(date));
    writeoffInstance.setItems(new ArrayList<>());
    String s = sendPost(JSONObject.toJSONString(writeoffInstance));
    ReimbursementInformation invoiceInfo = JSONObject.parseObject(s, ReimbursementInformation.class);
    return invoiceInfo;
  }
  
  @Override
  public ReimbursementInformation getReimbursementInformationByWriteoffInstanceCode(List<WriteoffInstanceCode> list) throws UnirestException {
    WriteoffInstance writeoffInstance = new WriteoffInstance();
    writeoffInstance.setItems(list);
    String s = sendPost(JSONObject.toJSONString(writeoffInstance));
    ReimbursementInformation invoiceInfo = JSONObject.parseObject(s, ReimbursementInformation.class);
    return invoiceInfo;
  }
  
  private String sendPost(String xml) throws UnirestException {
    //Unirest.setTimeouts(0, 0);
    HttpResponse<String> response = Unirest.post("http://134.96.253.66:8000/ESBWeb/servlets4Rest/zzs/intax/einvoice/synWriteoffInfo")
        .header("X-APP-ID", "9f20e0a3568f0ac014246713d4d4ba9b")
        .header("X-APP-KEY", "905bf65b4dc1be70190ad34a9e9fc320")
        .header("msgId", "123")
        .header("provinceCode", "02")
        .header("systemCode", "ZJ")
        .header("appid", "8136089511907229696")
        .header("Authorization", "Basic enBpdXNlcjE6WnBpYXBwbEAxMjM0")
        .header("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
        .header("Content-Type", "application/json")
        .body(xml)
        .asString();
    return response.getBody();
  }
}
